package com.lc.rabbitmq.controller;

import com.lc.rabbitmq.consumer.OrderConsumer;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.MessagePropertiesBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * @author liuc
 * @date 2021/8/16
 * @description
 **/
@RestController
public class OrderController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    OrderConsumer orderConsumer;

    @PostMapping("/order")
    public String order(){
        //下单
        MessageProperties properties = MessagePropertiesBuilder.newInstance()
                .setContentType("text/plain")
                .setContentEncoding("utf-8").build();
        String orderId = UUID.randomUUID().toString();
        Message message = MessageBuilder.withBody(("order:" + orderId).getBytes())
                .andProperties(properties)
                .build();
        orderConsumer.addOrder(orderId);
        rabbitTemplate.send("ex.pay","key.pay",message);
        return orderId;
    }


    @PutMapping("/pay")
    public String pay(@RequestParam("orderId") String orderId){
        //支付
        boolean f = orderConsumer.available(orderId);
        if(f){
            orderConsumer.pay(orderId);
            return "success";
        }else{
            return "fail";
        }
    }
}
